import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { TreeNode } from 'primeng/primeng';
import { flyIn } from '../../common/animation/common.animation';
import { SystemInfoService } from './service/sysinfo.service';

@Component({
  templateUrl: './sysinfo.component.html',
  styleUrls: ['./sysinfo.component.scss'],
  providers: [SystemInfoService],
  animations: [flyIn]
})
export class SysinfoComponent implements OnInit {
  loading: boolean = true;
  systems: TreeNode[];
  selectedSystem: TreeNode;
  suggestions: TreeNode[];
  suggestion: TreeNode;
  constructor(
    private sysInfoService: SystemInfoService,
    private route: ActivatedRoute,
    private router: Router) { }

  ngOnInit() {
    //初始化树控件
    this.initSysInfoTree("");
    //监听子组件中添加或删除事件，刷新树控件列表
    this.sysInfoService.routeMsgPush$.subscribe(data => this.initSysInfoTree(data));
  }
  /**初始化树控件 */
  initSysInfoTree(id: string) {
    this.sysInfoService.getSystemTree().subscribe(data => {
      this.loading = false
      this.systems = data;
      if (this.systems[0] && this.systems[0].children[0]) {
        if (id == "") {
          this.selectedSystem = this.systems[0].children[0];
        } else {
          this.systems[0].children.forEach(node => {
            if (node["id"] == data) {
              this.selectedSystem = node;
              return;
            }
          });
        }
        this.systemSelect(null);
      }
    });
  }
  /**树节点选中事件 */
  systemSelect(event) {
    this.router.navigate(['/system/sysinfo/detail', { "id": this.selectedSystem["id"] }]);
  }
  /**查询事件 */
  search(event) {
    this.suggestions = this.getSuggestionRecursive(event.query, this.systems, []);
  }
  /**查询选中事件 */
  selectSuggestion() {
    this.selectedSystem = this.suggestion;
  }

  getSuggestionRecursive(query: string, nodes: TreeNode[], dest: TreeNode[]) {
    nodes.forEach(node => {
      if (node.children) {
        node.children.forEach(childNode => {
          if (childNode.label.indexOf(query) != -1) {
            dest.push(childNode);
          }
        });
        this.getSuggestionRecursive(query, node.children, dest);
      }
    });
    return dest;
  }

}
